<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper">
      <a-form layout="vertical">
        <a-row :gutter="48">
          <a-col :md="8" :sm="12">
            <a-form-item label="学校代码">
              <a-input v-model="queryParam.xxdm"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="学校名称">
              <a-input v-model="queryParam.xxmc"/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="12">
              <a-form-item label="行政归属">
                <a-select
                  style="width:33%"
                  @change="provinceChange"
                  v-model="queryParam.xzqhsdm"
                  :allowClear="true"
                >
                  <a-select-option
                    v-for="i in selectMenu.province"
                    :key="i.areaCode"
                    :value="i.areaCode"
                  >{{ i.name }}</a-select-option>
                </a-select>
                <a-select
                  style="width:33%"
                  @change="cityChange"
                  v-model="queryParam.xzqhcdm"
                  :allowClear="true"
                >
                  <a-select-option
                    v-for="i in selectMenu.city"
                    :key="i.areaCode"
                    :value="i.areaCode"
                  >{{ i.name }}</a-select-option>
                </a-select>
                <a-select style="width:33%" v-model="queryParam.xzqhxdm" :allowClear="true">
                  <a-select-option
                    v-for="i in selectMenu.area"
                    :key="i.areaCode"
                    :value="i.areaCode"
                  >{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="12" :sm="24">
            <span
              class="table-page-search-submitButtons"

            >
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button type="primary" @click="openAdd">添加</a-button>
              <a-button type="primary" @click="batchDelete">删除</a-button>
              <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
              <a @click="advanced = !advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <school-edit
      ref="schoolEdit"
      :visible.sync="visible"
      :editId.sync="editId"
      :selectMenu.sync="selectMenu"
      @cancel="visible = false"
      @create="handleCreate"

    >
    </school-edit>
    <s-table ref="table"
             size="default"
             rowKey="key"
             :columns="columns"
             :data="loadData"
             :alert="options.alert"
             :rowSelection="options.rowSelection"
             :pagination="{ pageSize: 10 }"
    >
      <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>

      <a slot="operation" slot-scope="a,b" @click="openEdit(b)">修改</a>
    </s-table>
  </a-card>
</template>

<script>
import { STable } from '~'
import schoolEdit from './schoolEdit'
import moment from 'moment'

export default {
  components: {
    STable,
    schoolEdit
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: true,
      // 查询参数
      queryParam: {},
      postParams: {},
      // 表头
      columns: [
        {
          title: '序号1',
          scopedSlots: {customRender: 'serial'}
        },
        {
          title: '学校代码',
          dataIndex: 'xxdm'
        },
        {
          title: '学校名称',
          dataIndex: 'xxmc'
        },
        {
          title: '行政归属',
          dataIndex: 'xzqhsdmc'
        },
        {
          title: '学校性质',
          dataIndex: 'xxxzmc'
        },
        {
          title: '学校地址',
          dataIndex: 'xxdz'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.base.schoolInfoList(params).then(res => {
          return {
            data: res.data.rows,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: {
          show: true, clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true, // 是否显示alert，已选中
      visible: false,
      confirmLoading: false,
      selectMenu: {},
      editId: null
    }
  },
  created () {
    this.initSelectMenu()
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    initSelectMenu() {
      let allRequest = [this.$api.base.areaList()]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          province: res[0].data
        }
      })
    },
    handleCreate() {
      const form = this.$refs.schoolEdit.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        let baseApi = this.editId ? 'schoolInfoUpdate' : 'schoolInfoAdd'
        this.$api.base[baseApi](Object.assign({id: this.editId}, values)).then(res => {
          this.$message.success(res.msg)
          this.$refs.table.refresh(false)
        })
        form.resetFields()
        this.visible = false
      })
    },
    provinceChange (v) {
      this.$set(this.queryParam, 'xzqhcdm', '')
      this.$set(this.queryParam, 'xzqhxdm', '')
      if (v) {
        this.$api.base.areaList({ parentCode: v }).then(res => {
          this.$set(this.selectMenu, 'city', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'city', [])
      }
      this.$set(this.selectMenu, 'area', [])
    },
    cityChange (v) {
      this.$set(this.queryParam, 'xzqhxdm', '')
      if (v) {
        this.$api.base.areaList({ parentCode: v }).then(res => {
          this.$set(this.selectMenu, 'area', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'area', [])
      }
    },
    resetForm () {
      this.queryParam = {}
      this.selectMenu.city = []
      this.selectMenu.area = []
    },
    openAdd() {
      this.editId = null
      this.visible = true
      this.$set(this.selectMenu, 'zy', [])
      // this.$refs.schoolEdit.researchCode = new Array(3)
      this.$refs.schoolEdit.form.resetFields()
    },
    batchDelete() {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的学校')
        return
      }
      this.$confirm({
        title: '确定删除所选中的学校?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk: () => {
          let campusIds = []
          this.selectedRows.forEach(campus => {
            campusIds.push(campus.id)
          })
          this.$api.base.batchDeleteXxjbxx(campusIds.join(',')).then(() => {
            this.$message.success('删除成功')
            this.selectedRowKeys = []
            this.selectedRows = []
            this.$refs.table.refresh(false)
            this.$refs.table.clearSelected()
          })
        },
        onCancel: () => {
        }
      })
    },
    openEdit(school) {
      this.visible = true
      this.$nextTick(() => {
        if (school.jxny) {
          school.jxny = moment(school.jxny)
        }
        if (school.xzqhsdm) {
          this.$refs.schoolEdit.provinceChange(school.xzqhsdm)
        }
        if (school.xzqhcdm) {
          this.$refs.schoolEdit.cityChange(school.xzqhcdm)
        }
        this.$refs.schoolEdit.form.setFieldsValue(school)
        this.editId = school.id
      })
    }
  }
}
</script>
